import json
import os
import pymysql
# from flask import Flask, request
import cv2
import base64
import requests
import numpy as np
from test.database import Person,build_person_information_demo,init_database

# app = Flask(__name__)

global hukou_path
global family_path
global card_path
global table_person
global table_family
global table_card


def resize_and_encode_image(file):
    # 从 FileStorage 对象读取二进制数据
    image_data = file.read()
    # 将二进制数据转换为 numpy 数组
    image = np.frombuffer(image_data, np.uint8)
    # 解码图像
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
    # # 获取原始尺寸
    # original_height, original_width, _ = image.shape
    # # 计算缩减一半后的尺寸
    # new_width = original_width // 2
    # new_height = original_height // 2
    # # 调整图像尺寸
    # resized_image = cv2.resize(image, (new_width, new_height))
    # 将调整后的图像编码为 JPEG 格式
    _, encoded_image = cv2.imencode('.jpg', image)
    # 将编码后的图像转换为字节串
    byte_data = encoded_image.tobytes()
    # 进行 base64 编码
    base64_image = base64.b64encode(byte_data).decode('utf-8')
    # print(base64_image)
    return base64_image



def ask_llm(base64_image,query,i):
    url = "http://192.168.132.33:10253/v1/chat/completions"
    headers = {
        "Content-Type": "application/json"
    }
    messages = [{
        "role": "system",
        "content": [{"type": "text", "text": "图片表格解析"}]
    },
        {
            "role": "user",
            "content": [
                # {"type": "text", "text": "这张图片中的与户主关系有哪些？只有之兄、之弟、之姐、之妹、之夫、之妻、之子、之女这8种关系，没有的关系不要列出来。"},
                #     这张图片中的与户主关系有：\n\n- 之妻\n- 之女\n- 之女\n- 之兄",
                # {"type": "text", "text": "这张图片中户主是谁？户主之兄是谁？"},
                # 根据图片中的信息，户主是杨建国。户主之兄是杨建斌
                {"type": "text", "text":
                    query

                 },
                # {"type":"text","text":
                #     "要求你告诉我户主是谁，和户主所在列的信息"
                #     "需要你告诉我以下信息（没有的写无）：姓名、别名、性别、出生日期、民族、宗教信仰、籍贯。"
                # },
                # {"type": "text", "text": "这张图片中 李淑 的个人信息 包括：姓名、性别、出生日期、民族、宗教信仰、籍贯、出生地、婚姻状况、文化程度,没有就不写"},
                # 根据图片中的信息，李淑的个人信息如下：\n\n - 姓名：李淑\n - 性别：女\n - 出生日期：1924年6月8日\n - 民族：汉\n - 宗教信仰：无\n - 籍贯：河北石家庄石景山区\n - 职业及服务处所：农民\n - 何时由何地迁来本市：1944年10月21日从石家庄大王村迁来北京\n\n其他信息未填写。
                # {"type": "text", "text": "对文本纠错改正     这张图片中户主是杨建国，与户主有关系的其他人包括：\n\n - 之妻：李淑\n - 之女：杨雨晴\n - 之女：杨雨岚\n - 之男：杨建斌    根据图片中的信息，李淑的个人信息如下：\n\n - 姓名：李淑\n - 性别：女\n - 出生日期：1924年6月8日\n - 民族：汉\n - 宗教信仰：无\n - 籍贯：河北石家庄石景山区\n - 职业及服务处所：农民\n - 何时由何地迁来本市：1944年10月21日从石家庄大王村迁来北京\n\n其他信息未填写。"},
                {"type": "image_url", "image_url": base64_image}]

        }
    ]
    payload = {
        "model": "Qwen2-VL-7B-Instruct",
        "messages": messages,
        "stream": False,
        "max_tokens": 8192,
        "temperature": 0.01,
        "top_p": 0.9,
        "presence_penalty": 0.5,
        "frequency_penalty": 0.5,
    }
    response = requests.post(
        url,
        headers=headers,
        json=payload,
        timeout=600
    )

    data = json.loads(response.text)
    content = data["choices"][0]["message"]["content"]
    # with open('ttttt{}.json'.format(i), 'w', encoding='utf-8') as f:
    #     json.dump(content, f, indent=4, ensure_ascii=False)
    return content

def process_image(file,query_list):

    base64_image = resize_and_encode_image(file)

    responses =[]
    for i in range(len(query_list)):
        response = ask_llm(base64_image,query_list[i],i)
        responses.append(response)

    return responses

def insert_database(responses,image_path):
    # lines = responses[0].split('\n')
    person_list = []
    for i in range(len(responses)):
        #解析与户主关系
        if '与户主的关系' in responses[i]:
            lines = responses[i].split('\n')
            print('lines',lines)
            for line in lines:
                print('line',line)
                if '-' in line:
                    line = line.replace('-', '').replace(' ', '')
                    relation, name = line.split('：')
                    print(name,relation)
                    if i ==0:
                        person_list[i].relation='本人'
                    person_list[i+1].relation = relation

        else:
            lines = responses[i].replace(' ', '').split('\n')
            for line in lines:
                content_list = []
                line = line.replace(' ','')
                flag = line.split('：')[-1]
                print('flag',flag)
                #解析名字、性别、生日、民族,实例化person,本部分数据必须最先请求
                if '-' in line:
                    parts = line.split('-')
                    print(parts)
                    try:
                        name, gender, birthday, nationality = parts[0].split('.')[-1],parts[1],parts[2],parts[3]
                        person = Person(name=name,gender=gender,birthday=birthday,nationality=nationality)
                    except IndexError:
                        print("模型输出格式有误")
                        person = Person()
                    person.image_path = image_path
                    person.information_text = responses[i]
                    person_list.append(person)
                elif '：' in line and flag!='' and line and '.com' not in line:
                    parts = line.split('.')[-1].replace('"','').replace(' ','').split(',')
                    print('parts',parts)
                    for part in parts:
                        _,content=part.split('：')
                        content_list.append(content)

                    print(content_list)
                    try:
                        person = Person(name=content_list[0], gender=content_list[1], birthday=content_list[2], nationality=content_list[3])
                    except IndexError:
                        print("模型输出格式有误")
                        person = Person()
                    person.image_path = image_path
                    person.information_text = responses[i]
                    person_list.append(person)


    for person in person_list:
        person.print_all_parameters()
        person.insert_person_information(table_user=table_family)

def read_config():
    global hukou_path
    global family_path
    global card_path
    global table_person
    global table_family
    global table_card
    # 假设 JSON 数据存储在一个文件中，文件名为 example.json
    with open('./conf/config.json', 'r', encoding='utf-8') as f:
        data = json.load(f)

    # 解析 pic_paths
    pic_paths = data['pic_paths']
    hukou_path = pic_paths['hukou']
    family_path = pic_paths['family']
    card_path = pic_paths['card']

    # 解析 database_config
    database_config = data['database_config']
    tables = database_config['tables']

    # 解析表名
    table_person = tables['table_person']
    table_family = tables['table_family']
    table_card = tables['table_card']


def get_jpg_paths(folder_path):
    jpg_paths = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.jpg'):
                jpg_paths.append(os.path.join(root, file))
    return jpg_paths

def main():
    read_config()
    init_database()
    folder_path = family_path
    image_paths = get_jpg_paths(folder_path)

    try:

        build_person_information_demo(table=table_family)
    except pymysql.err.OperationalError as e:
        print("数据表{}已存在".format(table_family))

    name_relation_query = "要求你不看户主这列下的信息"\
                            "告诉我都有谁，与户主的关系分别是什么"\
                            "只用回答名字与关系"

    query_list = ["要求你告诉我表中人的姓名、性别、出生日期和民族（用换行符表示间隔）",name_relation_query]

    for image_path in image_paths:
        with open(image_path, 'rb') as file:
            image = file
            responses = process_image(image, query_list)
            insert_database(responses, image_path)





if __name__ == '__main__':
    main()



